package reflect;

import java.io.File;
import java.lang.reflect.Field;

/**
 * 通过反射机制访问属性
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws Exception {
        /*
        Person p = new Person();
        p.name = "张三";
        System.out.println(p.name);
         */
        Class cls = Class.forName("reflect.Person");
        Object obj = cls.newInstance(); //Person obj = new Person();
        /*
         Field是反射对象之一, 用于表示属性
         */
        Field field = cls.getDeclaredField("name"); //获取name属性
        field.setAccessible(true); //强制打开权限
        field.set(obj, "张三"); //obj.name = "张三"
        String name = (String) field.get(obj); //String name = obj.name;
        System.out.println("姓名:" + name);
        field.setAccessible(false); //关闭房间权限
        System.out.println("---------------------------------------------");

        Field field1 = cls.getDeclaredField("age"); //获取age属性
        field1.setAccessible(true);
        field1.set(obj, 25); //obj.age = 25;
        int age = (int) field1.get(obj); //int age = obj.age;
        System.out.println("年龄:" + age);
        field1.setAccessible(false);
        System.out.println("----------------------------------------------");

        System.out.println();
    }
}
